import 'package:flutter/material.dart';
import 'package:flutter_application_3/widgets/skeleton_item.dart';

class SliverDemo extends StatefulWidget {
  const SliverDemo({super.key});

  @override
  State<SliverDemo> createState() => _SliverDemoState();
}

class _SliverDemoState extends State<SliverDemo> {
  final List<String> _items = [];
  bool _isLoading = false;
  bool _isInitialLoading = true;
  String? _error;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _loadInitialData();
    
    // 添加滚动监听，实现上拉加载更多
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
          _scrollController.position.maxScrollExtent - 200) {
        _loadMoreData();
      }
    });
  }

  // 加载初始数据
  Future<void> _loadInitialData() async {
    try {
      setState(() {
        _isInitialLoading = true;
        _error = null;
      });

      // 模拟网络请求
      await Future.delayed(const Duration(seconds: 2));
      
      // 模拟空数据状态（随机）
      final bool hasData = DateTime.now().millisecondsSinceEpoch % 2 == 0;
      
      if (!mounted) return;

      setState(() {
        if (hasData) {
          _items.clear();
          _items.addAll(List.generate(15, (index) => 'Item ${index + 1}'));
        }
        _isInitialLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = e.toString();
        _isInitialLoading = false;
      });
    }
  }

  // 刷新数据
  Future<void> _refreshData() async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 2));
    if (!mounted) return;
    
    setState(() {
      _items.clear();
      _items.addAll(List.generate(15, (index) => 'Refreshed Item ${index + 1}'));
    });
  }

  // 加载更多数据
  Future<void> _loadMoreData() async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
    });

    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 1));
    if (!mounted) return;

    setState(() {
      _items.addAll(
        List.generate(5, (index) => 'New Item ${_items.length + index + 1}'),
      );
      _isLoading = false;
    });
  }

  // 构建空状态视图
  Widget _buildEmptyView() {
    return SliverFillRemaining(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.inbox_rounded,
              size: 80,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              '暂无数据',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _loadInitialData,
              child: const Text('重新加载'),
            ),
          ],
        ),
      ),
    );
  }

  // 构建错误状态视图
  Widget _buildErrorView() {
    return SliverFillRemaining(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 80,
              color: Colors.red[300],
            ),
            const SizedBox(height: 16),
            Text(
              '加载失败',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Text(
              _error ?? '未知错误',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[500],
              ),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _loadInitialData,
              child: const Text('重试'),
            ),
          ],
        ),
      ),
    );
  }

  // 更新加载状态视图
  Widget _buildLoadingView() {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) => const SkeletonItem(),
        childCount: 5, // 显示5个骨架项
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: _loadInitialData,
        child: CustomScrollView(
          controller: _scrollController,
          physics: const AlwaysScrollableScrollPhysics(),
          slivers: [
            SliverAppBar(
              expandedHeight: 200.0,
              floating: false,
              pinned: true,
              flexibleSpace: FlexibleSpaceBar(
                title: const Text('下拉刷新示例'),
                background: Image.network(
                  'https://picsum.photos/800/400',
                  fit: BoxFit.cover,
                ),
              ),
            ),

            // 根据状态显示不同的视图
            if (_isInitialLoading)
              _buildLoadingView()
            else if (_error != null)
              _buildErrorView()
            else if (_items.isEmpty)
              _buildEmptyView()
            else
              SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    if (index == _items.length) {
                      return _isLoading
                          ? const Padding(
                              padding: EdgeInsets.symmetric(vertical: 16),
                              child: Center(
                                child: SizedBox(
                                  width: 24,
                                  height: 24,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                  ),
                                ),
                              ),
                            )
                          : const SizedBox();
                    }

                    return Card(
                      margin: const EdgeInsets.symmetric(
                        horizontal: 15,
                        vertical: 5,
                      ),
                      child: ListTile(
                        title: Text(_items[index]),
                        subtitle: Text('这是第 ${index + 1} 个项目'),
                        leading: CircleAvatar(
                          backgroundColor: Colors.primaries[index % Colors.primaries.length],
                          child: Text('${index + 1}'),
                        ),
                      ),
                    );
                  },
                  childCount: _items.length + 1,
                ),
              ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _scrollController.animateTo(
            0,
            duration: const Duration(milliseconds: 500),
            curve: Curves.easeInOut,
          );
        },
        child: const Icon(Icons.arrow_upward),
      ),
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
} 